﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using medicine.DAL.DataSet1TableAdapters ;
using System.Data.OleDb;
using medicine.DAL;
using System.Collections;
using medicine.General;
using medicine.Forms.ItemSelection;
using System.Data.Common;
using medicine.BaseComponents.Groups;

namespace medicine
{
    public partial class ItemSelectionFRM : Form
    {
        private GroupInfo _GI;
        private GroupLabel _LB;
        public List<string> _Selected = new List<string>();

        public ItemSelectionFRM()
        {
            InitializeComponent();
        }

        public DialogResult ShowDialog(IWin32Window owner, GroupLabel LB)
        {
            //this._Selected= LB.GroupInfo.Selected;
            this._Selected.Clear();
            foreach (string item in LB.GroupInfo.Selected)
            {
                this._Selected.Add(item);
            }
            this._GI = LB.GroupInfo ;
            this._LB = LB;
            return this.ShowDialog(owner);
        }

        private void Form2_Load(object sender, EventArgs e)
        {
            Application.DoEvents();
            InitilizeComp();
        }

        private void InitilizeComp()
        {
            this.Text = "Item Selection - " + this._GI.Text;
            if (this._GI.isColumn)
                cmdQuery.Enabled = false;
            Application.DoEvents();
            LoadData();
            WriteTotals();
        }

        private void LoadData()
        {
            LoadData(false,false, "", ItemSelectionFindFRM.eFindMode.AnyWhere, false);
        }

        private void LoadData(bool isQuery,bool withFilters,string FilterString,ItemSelectionFindFRM.eFindMode findMode,bool MatchCase)
        {
            lstAvailable.Items.Clear();
            lstSelected.Items.Clear();
            //string SSQL = "SELECT " + this._GI.DBValueField + ", " + this._GI.DBDisplayField + " FROM " + this._GI.DBTableName;
            if (this._GI.DBTableName != string.Empty && this._GI.DBValueField != string.Empty && this._GI.DBDisplayField != string.Empty)
            {
                //string SSQL = MedicineDBStructure.GetSelectStatment(this._GI.DBTableName, this._GI.DBValueField, this._GI.DBDisplayField,"","");
                //OleDbDataReader dr = OleDbUtilities.ExecuteDataReader(SSQL);
                DbDataReader dr = this._GI.GetDataReader(isQuery,MedicinUtilities.GetSQLFilter(this._GI.Text));
                if (isQuery && !dr.HasRows)
                    MessageBox.Show("No Database Records were Selected", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                while (dr.Read())
                {
                    if (this._Selected.Contains(dr[this._GI.DBValueField].ToString()))
                    {
                        ListBoxItem PrevItem = isItemAlreadyExists(dr[this._GI.DBDisplayField].ToString());
                        if (PrevItem==null)
                            lstSelected.Items.Add(new ListBoxItem(dr[this._GI.DBDisplayField].ToString(), dr[this._GI.DBValueField].ToString()));                            
                        else
                            PrevItem.AddRelated(new ListBoxItem(dr[this._GI.DBDisplayField].ToString(), dr[this._GI.DBValueField].ToString()));
                    }
                    else
                    {
                        //---------------------------------------------------------------------------
                        // Find 
                        string SearchDisplayText = dr[this._GI.DBDisplayField].ToString();
                        bool ShouldAdd = true;
                        if (withFilters)
                        {
                            if (!MatchCase)
                            {
                                SearchDisplayText = SearchDisplayText.ToLower();
                                FilterString = FilterString.ToLower();
                            }
                            if (findMode == ItemSelectionFindFRM.eFindMode.AnyWhere)
                                ShouldAdd = SearchDisplayText.Contains(FilterString);
                            if (findMode == ItemSelectionFindFRM.eFindMode.Beginning)
                                ShouldAdd = SearchDisplayText.StartsWith(FilterString);
                            if (findMode == ItemSelectionFindFRM.eFindMode.end)
                                ShouldAdd = SearchDisplayText.EndsWith(FilterString);

                        }
                        //---------------------------------------------------------------------------
                        if (ShouldAdd)
                        {
                            ListBoxItem PrevItem = isItemAlreadyExists(dr[this._GI.DBDisplayField].ToString());
                            if (PrevItem == null)
                                lstAvailable.Items.Add(new ListBoxItem(dr[this._GI.DBDisplayField].ToString(), dr[this._GI.DBValueField].ToString()));
                            else
                                PrevItem.AddRelated(new ListBoxItem(dr[this._GI.DBDisplayField].ToString(), dr[this._GI.DBValueField].ToString()));
                        }

                    }
                }
            }
        }

        private ListBoxItem isItemAlreadyExists(string Text)
        {
            foreach (ListBoxItem item in lstAvailable.Items)
            {
                if (item.Text == Text)
                    return item;
            }

            foreach (ListBoxItem item in lstSelected.Items)
            {
                if (item.Text == Text)
                    return item;
            }
            return null;
        }

        private void WriteTotals()
        {
            lblMarkedunselected.Text = lstAvailable.SelectedIndices.Count.ToString() + " of " + lstAvailable.Items.Count.ToString() + " members marked";
            lblMarkedSelected.Text = lstSelected.SelectedIndices.Count.ToString() + " of " + lstSelected.Items.Count.ToString() + " members marked";
        }

        private void cmdSelectAll_Click(object sender, EventArgs e)
        {
            foreach (object item in lstAvailable.Items)
            {
                lstSelected.Items.Add(item);
                this._Selected.Add(((ListBoxItem)item).Value);
            }
            lstAvailable.Items.Clear();
            WriteTotals();
        }

        private void cmdSelect_Click(object sender, EventArgs e)
        {
            ArrayList temp = new ArrayList();
            foreach (object item in lstAvailable.SelectedItems)
            {
                lstSelected.Items.Add(item);
                temp.Add(item);
                this._Selected.Add(((ListBoxItem)item).Value);
            }
            foreach (object item in temp)
            {
                lstAvailable.Items.Remove(item);                
            }
        }

        private void cmdUnSelect_Click(object sender, EventArgs e)
        {
            ArrayList temp = new ArrayList();
            foreach (object item in lstSelected.SelectedItems)
            {
                lstAvailable.Items.Add(item);
                temp.Add(item);
            }
            foreach (object item in temp)
            {
                lstSelected.Items.Remove(item);
                this._Selected.Remove(((ListBoxItem)item).Value);
            }

        }

        private void cmdUnSelectAll_Click(object sender, EventArgs e)
        {
            foreach (object item in lstSelected.Items)
            {
                lstAvailable.Items.Add(item);
                
            } 
            lstSelected.Items.Clear();
            this._Selected.Clear();
            WriteTotals();
        }

        private void lstAvailable_SelectedIndexChanged(object sender, EventArgs e)
        {
            

            WriteTotals();            

#if (DEBUG)
            bool UseDebug = false;
            if (lstAvailable.SelectedIndex>=0)
            {
                if (_GI.DBTableName == "Periods")
                {
                    DateTime StudyDate = DateTime.Now;
                    if (medicine.DAL.MedicineDBStructure.StudyDate != null)
                        StudyDate = (DateTime)medicine.DAL.MedicineDBStructure.StudyDate; 

                    PeriodClass CurrentPeriod = PeriodClass.DeSerialize(((ListBoxItem)lstAvailable.Items[lstAvailable.SelectedIndex]).Value);
                    lblStartDate.Text = "FROM: " + CurrentPeriod.FromDate.ToString("dd/MM/yyyy");
                    lblEndDate.Text = "TO   : " + CurrentPeriod.ToDate.ToString("dd/MM/yyyy");
                    lblLength.Text = "Len: " + CurrentPeriod.PeriodLength.ToString() + " Months";
                    lblStudyDate.Text = "StudyDate: " + StudyDate.ToString("dd/MM/yyyy");
                    UseDebug=true;
                }
            }
            if (!UseDebug)
            {
                lblStartDate.Visible = false; lblEndDate.Visible = false; lblLength.Visible = false; lblStudyDate.Visible = false;
            }
            else
            {
                lblStartDate.Visible = true; lblEndDate.Visible = true; lblLength.Visible = true; lblStudyDate.Visible = true;
            }
#else
    lblStartDate.Visible=false; lblEndDate.Visible=false; lblLength.Visible=false; lblStudyDate.Visible = false;
#endif

        }

        private void cmdOK_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.OK;
            this._LB.GroupInfo.Selected.Clear();
            foreach (ListBoxItem item in lstSelected.Items)
            {
                this._LB.GroupInfo.Selected.Add(item.Value);
                foreach (ListBoxItem item2 in item.RelatedItems)
                {
                    this._LB.GroupInfo.Selected.Add(item2.Value );
                }
                
            }
            this.Close();
        }


        private void cmdCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();

        }

        private void lstSelected_SelectedIndexChanged(object sender, EventArgs e)
        {
            WriteTotals();
        }

        private void txtDisplayUnselected_TextChanged(object sender, EventArgs e)
        {
            FindTextinListBoxAndMakeITTopItem(txtDisplayUnselected, lstAvailable);
        }

        private void txtDisplaySelected_TextChanged(object sender, EventArgs e)
        {
            FindTextinListBoxAndMakeITTopItem(txtDisplaySelected, lstSelected);
        }

        private void FindTextinListBoxAndMakeITTopItem(TextBox Txt, ListBox lst)
        {
            errorProvider1.SetError(Txt, null);
            if (Txt.Text == string.Empty)
                return;

            int index = -1;
            string SearchText = Txt.Text.ToLower().Trim();
            foreach (ListBoxItem item in lst.Items)
            {
                if (item.Text.ToLower().StartsWith(SearchText))
                {
                    index = lst.Items.IndexOf(item);
                    break;
                }
            }

            if (index > -1)
                lst.TopIndex = index;
            else
                errorProvider1.SetError(Txt, "Not found");
        }

        private void cmdOptions_Click(object sender, EventArgs e)
        {
            new ItemSelectionOptionsFRM().ShowDialog(this);
        }

        private void cmdFind_Click(object sender, EventArgs e)
        {
            ItemSelectionFindFRM FindFRM = new  ItemSelectionFindFRM();
            if (DialogResult.OK == FindFRM.ShowDialog(this))
            {
                LoadData(false,true, FindFRM.FilterText, FindFRM.FindMode, FindFRM.MatchCase);
                WriteTotals();
            }
        }

        private void cmdShowAll_Click(object sender, EventArgs e)
        {
            LoadData();
            WriteTotals();

        }

        private void cmdQuery_Click(object sender, EventArgs e)
        {
            LoadData(true, false, "", ItemSelectionFindFRM.eFindMode.AnyWhere, false);
            WriteTotals();
            //MessageBox.Show(MedicineDBStructure.GetAllRealtionsAsSQL(_GI.DBTableName));
            //MedicineDBStructure.GetAllRelations(_GI.DBTableName);
        }

    }
}
